<template>
  <div>
    <div class="ccui-multifunctional-table-wrapper" style="marign-top: 10px">
      <div
        style="
          width: 100%;
          height: 50px;
          backgroung: red;
          display: flex;
          justify-content: flex-end;
        "
      >
        <dialogMultiSelectTable
          btnText="选择库存"
          dialogTitle="选择库存"
          onlyKey="batchNumber"
          :isShow="getInventoryStatus"
          isOpenSearch
          errorMessage="请先选择仓库"
          :searchInputArr="jsList.searchInputArr"
          :tableHeadOptions="jsList.tableHeadOptions"
          :getTableList="listSmpStockForInventoryPage"
          :optionalParams="planOptionalParams"
          @confirm="planConfirm"
        />
        <el-button
          size="mini"
          plain
          type="single-number"
          @click="deleteRow()"
          style="margin-left: 20px"
          >删除行</el-button
        >
      </div>
      <ux-grid
        align="center"
        ref="multipleTable"
        border
        class="ccui-multifunctional-table"
        :summary-method="getSummaries"
        lazy
        show-summary
        keep-source
        max-height="9999"
        show-overflow
        :highlightCurrentRow="false"
        :widthResize="true"
        :header-cell-class-name="must"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        @selection-change="handleSelectionChange"
      >
        <ux-table-column type="checkbox" width="50" fixed="left" />
        <ux-table-column type="index" title="序号" width="50" fixed="left" />
        <ux-table-column
          title="批次号"
          field="batchNumber"
          width="200"
          fixed="left"
          show-overflow-tooltip
        />
        <ux-table-column
          title="设备物资编码"
          field="materialCode"
          width="110"
          show-overflow-tooltip
        />
        <ux-table-column
          title="设备物资名称"
          field="materialName"
          width="260"
          show-overflow-tooltip
        />
        <ux-table-column
          title="设备物资说明"
          field="materialState"
          width="130"
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input
              maxlength="500"
              placeholder="请输入设备物资说明"
              v-model="row.materialState"
              show-word-limit
            >
            </el-input>
          </template>
          <template v-slot="scope">
            <span class="my-input-sc">{{ scope.row.materialState }}</span>
          </template>
        </ux-table-column>
        <ux-table-column
          title="分类名称"
          field="categoryName"
          width="170"
          show-overflow-tooltip
        />
        <ux-table-column
          title="计量单位"
          field="measureUnit"
          width="90"
          show-overflow-tooltip
        />
        <ux-table-column
          title="库存数量"
          field="storageCount"
          width="120"
          header-align="left"
        />
        <ux-table-column
          title="可用库存数量"
          field="unStorageCount"
          width="130"
          header-align="left"
        />
        <!-- transferLibraryCount 移库数量 -->
        <ux-table-column
          title="移库数量"
          field="transferLibraryCount"
          width="130"
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input
              placeholder="请输入移库数量"
              v-model="row.transferLibraryCount"
              @blur="changeNum($event, row)"
              clearable
            >
            </el-input>
          </template>
          <template v-slot="scope">
            <span class="my-input-sc">{{
              scope.row.transferLibraryCount
            }}</span>
          </template>
        </ux-table-column>
        <ux-table-column
          title="币种"
          field="currencyName"
          width="100"
          header-align="left"
        />
        <ux-table-column
          title="汇率"
          field="exchangeRate"
          width="100"
          header-align="left"
        />
        <ux-table-column
          title="含税单价"
          field="unitPriceWithTax"
          width="100"
          align="right"
          header-align="left"
        />
        <ux-table-column
          title="含税金额"
          field="moneyWithTax"
          width="100"
          align="right"
          header-align="left"
        />

        <ux-table-column
          title="备注"
          field="remark"
          width="200"
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input maxlength="1000" placeholder="请输入备注" v-model="row.remark" show-word-limit> </el-input>
          </template>
          <template v-slot="scope">
            <span class="my-input-sc">{{ scope.row.remark }}</span>
          </template>
        </ux-table-column>
      </ux-grid>
    </div>
    <!-- <dialog-multi-select-table
            ref="dialogMultiSelectTable"
            :searchInputArr="jsList.searchInputArr"
            :tableHeadOptions="jsList.tableHeadOptions"
            :selectTableList="[]"
            :optionalParams="optionalParams"
            :mode="mode"
            :warehouseId="originalWarehouseId"
            @confirm="confirm"
        /> -->
  </div>
</template>

<script>
// import dialogMultiSelectTable from "./selectHouse.vue";
import dialogMultiSelectTable from "@/basa/components/public/dialogMultiSelectTable";
import jsList from "../js/index";
import { formatNumber } from "@/basa/utils";
// import { formatNumber } from "@/basa/utils";
import { listSmpStockForInventoryPage } from "../api";
import { mapGetters } from "vuex";
import { uniqueByJson } from "@/basa/utils";
export default {
  props: {
    // 原仓库id
    originalWarehouseId: {
      type: Number
    },
    // 目标仓库
    targetWarehouseId: {
      type: Number
    },
    purchaseData: {
      type: Array,
      default: () => []
    }
  },
  components: { dialogMultiSelectTable },
  watch: {
    purchaseData: {
      handler(data) {
        console.log(data);
        this.tableData = data;
        this.$nextTick(() => {
          this.$refs.multipleTable.reloadData(this.tableData);
        });
      },
      immediate: true
      //   deep: true
    },
    originalWarehouseId: {
      handler(val) {
        if (val) {
          this.planOptionalParams = {
            ...this.planOptionalParams,
            warehouseId: val
          };
        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      jsList,
      tableData: [], //列表数据
      timer: null,
      tableLoading: null,
      optionalParams: {},
      mode: "checkbox",
      planOptionalParams: {},
      selectVal: []
    };
  },
  computed: {
    ...mapGetters(["getWarehouseId", "getInventoryStatus"])
  },
  methods: {
    listSmpStockForInventoryPage,
    planConfirm(arr) {
      let arr1 = arr.map(item => ({
        ...item,
        flag: true,
        materialId: item.id,
        storageCount: formatNumber(Number(item.actualStockCount), 3), //库存数量
        unStorageCount: formatNumber(Number(item.availableStockCount), 3), //可用库存数量
        unitPriceWithTax: Number(item.unitPriceWithTax).toFixed(2), //含税单价
        moneyWithTax: Number(item.moneyWithTax).toFixed(2), //含税金额
        transferLibraryCount: Number(item.availableStockCount !== null ? item.availableStockCount : 0).toFixed(3),
      }));
      this.tableData = uniqueByJson(
        [...this.tableData, ...arr1],
        "batchNumber"
      );
      this.$nextTick(() => {
        this.$refs.multipleTable.reloadData(this.tableData);
      });
      this.$bus.$emit("getCategoryName", this.tableData[0]);
    },
    // 多选框选择数据
    handleSelectionChange(val) {
      this.selectVal = val;
    },
    // pageNo: 1
    // pageSize: 10
    // 选择库存
    getHouse() {
      if (!this.originalWarehouseId || !this.targetWarehouseId) {
        this.$showErrorMessage("请先选择仓库！");
      } else {
        this.$refs.dialogMultiSelectTable.showDialogVisible = true;
        this.$refs.dialogMultiSelectTable.getListSmpStockForInventoryPage(
          this.$refs.dialogMultiSelectTable.inventoryForm
        );
      }
    },
    // 删除行
    deleteRow() {
      if (this.selectVal.length <= 0) {
        this.$showErrorMessage("请至少选择一项");
        return;
      }
      var that = this;
      // 拿到选中的数据；
      var val = this.selectVal;
      // 如果选中数据存在
      if (val) {
        // 将选中数据遍历
        val.forEach(function (item, index) {
          // 遍历源数据
          that.tableData.forEach(function (itemI, indexI) {
            // 如果选中数据跟元数据某一条标识相等，删除对应的源数据
            if (item.id === itemI.id) {
              that.tableData.splice(indexI, 1);
            }
          });
        });
      }
      this.$refs.multipleTable.reloadData(this.tableData);
      this.$bus.$emit("getCategoryName", that.tableData[0]);
      // 清除选中状态
      this.$refs.multipleTable.clearSelection();
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (
          [
            "storageCount",
            "unStorageCount",
            "transferLibraryCount",
            "moneyWithTax"
          ].includes(column.property)
        ) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                let num = Number(prev) + Number(curr);
                return num;
              } else {
                return Number(prev);
              }
            }, 0);
            if (column.title == "库存数量") {
              sums[index] = sums[index]
                ? formatNumber(Number(sums[index]), 3)
                : "";
            }
            if (column.title == "移库数量") {
              sums[index] = sums[index]
                ? formatNumber(Number(sums[index]), 3)
                : formatNumber(0, 3);
              //   this.$bus.$emit("getMoveNum", Number(sums[index]));
              console.log("xxxx");
              this.$store.commit("setMoveInventoryCount", Number(sums[index]));
              this.$emit("getCount", Number(sums[index]));
            }
            if (column.title == "可用库存数量") {
              sums[index] = sums[index]
                ? formatNumber(Number(sums[index]), 3)
                : "";
            }
            if (column.title == "含税金额") {
              sums[index] = sums[index] ? Number(sums[index]).toFixed(2) : "";
              //   this.$bus.$emit("getMoveMoney", Number(sums[index]));
              console.log("xxxx");
              this.$store.commit("setMoveInventoryMoney", Number(sums[index]));
              this.$emit("getMoney", Number(sums[index]));
            }
          }
        }
      });
      return [sums];
    },
    must(obj) {
      if (obj.columnIndex == 10) {
        return "must";
      }
    },
    // 输入移库数量
    changeNum(e, row) {
      if (isNaN(e.target.value * 1)) {
        // row.bowOutNumber = 0;
        row.transferLibraryCount = formatNumber(0, 3);
      } else {
        if (e.target.value * 1 <= 0) {
          // row.transferLibraryCount = 0;
          row.transferLibraryCount = formatNumber(0, 3);
        } else {
          row.transferLibraryCount = formatNumber(e.target.value, 3);
          let moveTotal =
            Number(row.unitPriceWithTax) * Number(row.transferLibraryCount);
          this.$set(row, "moneyWithTax", Number(moveTotal).toFixed(2)); //含税金额 = 移库数量*含税单价
          // 不含税单价=含税单价/(1+税率)
          let firsNum = 1 + Number(row.taxRate);
        //   console.log("1+税率", firsNum);
          let secondNum = (Number(row.moneyWithTax) / firsNum).toFixed(2);
          this.$set(row, "moneyWithoutTax", secondNum);
        //   console.log("不含税金额", secondNum);
        }
      }
    }
  },
  created() {
    this.$bus.$on("resetPurchase", message => {
    //   console.log(message);
      this.tableData = message;
      this.$nextTick(() => {
        this.$refs.multipleTable.reloadData(this.tableData);
      });
    });
  }
  //   deactivated(){
  //       this.$bus.$off('resetPurchase');
  //   }
};
</script>

<style lang="scss" scoped>
/deep/ .elx-table .elx-footer--column {
  font-weight: bolder;
}
/deep/ .el-table th.must > .cell:before {
  content: "* ";
  color: #ff1818;
}
::v-deep {
      .el-input input {
        padding-right: 50px;
      }
    }
</style>
